package net.sxnic.ugr;

import net.sxnic.comm.CommActionSupport;
import net.sxnic.ugr.context.AppContext;
import net.sxnic.ugr.security.AuthorizationManager;
import net.sxnic.ugr.security.UnauthorizedException;
import net.sxnic.ugr.user.User;
import net.sxnic.ugr.user.UserManager;

import org.springframework.beans.factory.annotation.Autowired;

@SuppressWarnings("serial")
public class UgrActionSupport extends CommActionSupport {
	
	public final static String LOGIN="preLogin";

	@Autowired
	protected AuthorizationManager authorizationManager;

	@Autowired
	protected UserManager userManager;
	
	protected void addActionMessage(String msg){
		
	}
		
	protected void addActionError(String msg){
		
	}	

	protected String getText(String txt){
		return txt;
	}
	
	protected String getText(String txt,String[] names){
		return txt;
	}

	/**
	 * 验证当前用户是否有roles中包含的权限
	 * 
	 * @param roles
	 */
	protected void checkRoles(String... roles) {
		  
		User user = userManager.getUserByUsername(AppContext
				.getUserName(request));
		 
		for (String r : roles) {
			if (!authorizationManager.isUserInRole(user, r)) {
				notAuthorized();
			}
		}
	}

	protected void checkRolesWithRule(String rule, String... roles) {
		if (!authorizationManager.isInRole(rule, roles)) {
			notAuthorized();
		}
	}

	protected void isUserInRole(User u, String role) {
		if (!authorizationManager.isUserInRole(u, role)) {
			notAuthorized();
		}
	}

	protected void notAuthorized() {
		throw new UnauthorizedException();
	}

}
